'''
-*- coding: utf-8 -*-
@File  : Rtsp.py
@Author: Shanmh
@Time  : 2024/03/01 下午1:54
@Function：
'''
import queue
import subprocess
import traceback

import cv2

import glob
import math
import os
import time
from dataclasses import dataclass
from pathlib import Path
from threading import Thread
from urllib.parse import urlparse
import re
import cv2
import numpy as np
import requests
import torch
from PIL import Image
from loguru import logger
IMG_FORMATS = 'bmp', 'dng', 'jpeg', 'jpg', 'mpo', 'png', 'tif', 'tiff', 'webp', 'pfm'  # image suffixes
VID_FORMATS = 'asf', 'avi', 'gif', 'm4v', 'mkv', 'mov', 'mp4', 'mpeg', 'mpg', 'ts', 'wmv', 'webm'  # video suffixes

# logger.add(sink='log/log_{time}_pull.log',filter=lambda x: '[pull]' in x['message'], enqueue=True,rotation='00:00', retention="7 days")
class LoadImages:
    """YOLOv8 image/video dataloader, i.e. `yolo predict source=image.jpg/vid.mp4`."""

    def __init__(self, path, imgsz=640, vid_stride=1):
        """Initialize the Dataloader and raise FileNotFoundError if file not found."""
        parent = None
        if isinstance(path, str) and Path(path).suffix == '.txt':  # *.txt file with img/vid/dir on each line
            parent = Path(path).parent
            path = Path(path).read_text().splitlines()  # list of sources
        files = []
        for p in sorted(path) if isinstance(path, (list, tuple)) else [path]:
            a = str(Path(p).absolute())  # do not use .resolve() https://github.com/ultralytics/ultralytics/issues/2912
            if '*' in a:
                files.extend(sorted(glob.glob(a, recursive=True)))  # glob
            elif os.path.isdir(a):
                files.extend(sorted(glob.glob(os.path.join(a, '*.*'))))  # dir
            elif os.path.isfile(a):
                files.append(a)  # files (absolute or relative to CWD)
            elif parent and (parent / p).is_file():
                files.append(str((parent / p).absolute()))  # files (relative to *.txt file parent)
            else:
                raise FileNotFoundError(f'{p} does not exist')

        images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS]
        videos = [x for x in files if x.split('.')[-1].lower() in VID_FORMATS]
        ni, nv = len(images), len(videos)

        self.imgsz = imgsz
        self.files = images + videos
        self.nf = ni + nv  # number of files
        self.video_flag = [False] * ni + [True] * nv
        self.mode = 'image'
        self.vid_stride = vid_stride  # video frame-rate stride
        self.bs = 1
        if any(videos):
            self._new_video(videos[0])  # new video
        else:
            self.cap = None
        if self.nf == 0:
            raise FileNotFoundError(f'No images or videos found in {p}. '
                                    f'Supported formats are:\nimages: {IMG_FORMATS}\nvideos: {VID_FORMATS}')

    def __iter__(self):
        """Returns an iterator object for VideoStream or ImageFolder."""
        self.count = 0
        return self

    def __next__(self):
        """Return next image, path and metadata from dataset."""
        if self.count == self.nf:
            raise StopIteration
        path = self.files[self.count]

        if self.video_flag[self.count]:
            # Read video
            self.mode = 'video'
            for _ in range(self.vid_stride):
                self.cap.grab()
            success, im0 = self.cap.retrieve()
            while not success:
                self.count += 1
                self.cap.release()
                if self.count == self.nf:  # last video
                    raise StopIteration
                path = self.files[self.count]
                self._new_video(path)
                success, im0 = self.cap.read()

            self.frame += 1
            # im0 = self._cv2_rotate(im0)  # for use if cv2 autorotation is False
            s = f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: '

        else:
            # Read image
            self.count += 1
            im0 = cv2.imread(path)  # BGR
            if im0 is None:
                raise FileNotFoundError(f'Image Not Found {path}')
            s = f'image {self.count}/{self.nf} {path}: '

        return [path], [im0], self.cap, s

    def _new_video(self, path):
        """Create a new video capture object."""
        self.frame = 0
        self.cap = cv2.VideoCapture(path)
        self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT) / self.vid_stride)

    def __len__(self):
        """Returns the number of files in the object."""
        return self.nf  # number of files

class LoadStreams:
    """YOLOv8 streamloader, i.e. `yolo predict source='rtsp://example.com/media.mp4'  # RTSP, RTMP, HTTP streams`."""

    def __init__(self, sources='file.streams', imgsz=None, vid_stride=1, buffer=False):
        """Initialize instance variables and check for consistent input stream shapes."""
        # torch.backends.cudnn.benchmark = True  # faster for fixed-size inference
        self.buffer = buffer  # buffer input streams
        self.running = True  # running flag for Thread
        self.mode = 'stream'
        self.imgsz = imgsz
        self.vid_stride = vid_stride  # video frame-rate stride

        sources = Path(sources).read_text().rsplit() if os.path.isfile(sources) else [sources]
        n = len(sources)
        self.sources = [re.sub(pattern='[|@#!¡·$€%&()=?¿^*;:,¨´><+]', repl='_', string=s) for s in sources]  # clean source names for later
        self.imgs, self.fps, self.frames, self.threads, self.shape = [[]] * n, [0] * n, [0] * n, [None] * n, [[]] * n
        self.caps = [None] * n  # video capture objects
        for i, s in enumerate(sources):  # index, source
            # Start thread to read frames from video stream
            st = f'{i + 1}/{n}: {s}... '
            if urlparse(s).hostname in ('www.youtube.com', 'youtube.com', 'youtu.be'):  # if source is YouTube video
                # YouTube format i.e. 'https://www.youtube.com/watch?v=Zgi9g1ksQHc' or 'https://youtu.be/LNwODJXcvt4'
                s = get_best_youtube_url(s)
            s = eval(s) if s.isnumeric() else s  # i.e. s = '0' local webcam
            self.caps[i] = cv2.VideoCapture(s)  # store video capture object
            if not self.caps[i].isOpened():
                raise ConnectionError(f'{st}Failed to open {s}')
            w = int(self.caps[i].get(cv2.CAP_PROP_FRAME_WIDTH))
            h = int(self.caps[i].get(cv2.CAP_PROP_FRAME_HEIGHT))
            fps = self.caps[i].get(cv2.CAP_PROP_FPS)  # warning: may return 0 or nan
            self.frames[i] = max(int(self.caps[i].get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float(
                'inf')  # infinite stream fallback
            self.fps[i] = max((fps if math.isfinite(fps) else 0) % 100, 0) or 30  # 30 FPS fallback

            success, im = self.caps[i].read()  # guarantee first frame
            if not success or im is None:
                raise ConnectionError(f'{st}Failed to read images from {s}')
            self.imgs[i].append(im)
            self.shape[i] = im.shape
            self.threads[i] = Thread(target=self.update, args=([i, self.caps[i], s]), daemon=True)
            logger.info(f'[pull] {st}Success ✅ ({self.frames[i]} frames of shape {w}x{h} at {self.fps[i]:.2f} FPS)')
            self.threads[i].start()
        logger.info('[pull] ')  # newline

        # Check for common shapes
        self.bs = self.__len__()

    def update(self, i, cap, stream):
        """Read stream `i` frames in daemon thread."""
        n, f = 0, self.frames[i]  # frame number, frame array
        while self.running and cap.isOpened() and n < (f - 1):
            if len(self.imgs[i]) < 1:  # keep a <=30-image buffer
                n += 1
                cap.grab()  # .read() = .grab() followed by .retrieve()
                if n % self.vid_stride == 0:
                    success, im = cap.retrieve()
                    if not success:
                        im = np.zeros(self.shape[i], dtype=np.uint8)
                        logger.warning('[pull] WARNING ⚠️ Video stream unresponsive, please check your IP camera connection.')
                        cap.open(stream)  # re-open stream if signal was lost
                    if not self.imgsz is None:
                        im=cv2.resize(im,self.imgsz,cv2.INTER_LINEAR)
                    if self.buffer:
                        self.imgs[i].append(im)
                    else:
                        self.imgs[i] = [im]
            else:
                time.sleep(0.01)  # wait until the buffer is empty

    def close(self):
        """Close stream loader and release resources."""
        self.running = False  # stop flag for Thread
        for thread in self.threads:
            if thread.is_alive():
                thread.join(timeout=5)  # Add timeout
        for cap in self.caps:  # Iterate through the stored VideoCapture objects
            try:
                cap.release()  # release video capture
            except Exception as e:
                logger.warning(f'[pull] WARNING ⚠️ Could not release VideoCapture object: {e}')
        cv2.destroyAllWindows()

    def __iter__(self):
        """Iterates through YOLO image feed and re-opens unresponsive streams."""
        self.count = -1
        return self

    def __next__(self):
        """Returns source paths, transformed and original images for processing."""
        self.count += 1

        images = []
        for i, x in enumerate(self.imgs):

            # Wait until a frame is available in each buffer
            while not x:
                if not self.threads[i].is_alive() or cv2.waitKey(1) == ord('q'):  # q to quit
                    self.close()
                    raise StopIteration
                time.sleep(1 / min(self.fps))
                x = self.imgs[i]
                if not x:
                    logger.warning(f'[pull] WARNING ⚠️ Waiting for stream {i}')

            # Get and remove the first frame from imgs buffer
            if self.buffer:
                images.append(x.pop(0))

            # Get the last frame, and clear the rest from the imgs buffer
            else:
                images.append(x.pop(-1) if x else np.zeros(self.shape[i], dtype=np.uint8))
                x.clear()

        return self.sources, images, None, ''

    def __len__(self):
        """Return the length of the sources object."""
        return len(self.sources)  # 1E12 frames = 32 streams at 30 FPS for 30 years

def get_best_youtube_url(url, use_pafy=False):
    """
    Retrieves the URL of the best quality MP4 video stream from a given YouTube video.

    This function uses the pafy or yt_dlp library to extract the video info from YouTube. It then finds the highest
    quality MP4 format that has video codec but no audio codec, and returns the URL of this video stream.

    Args:
        url (str): The URL of the YouTube video.
        use_pafy (bool): Use the pafy package, default=True, otherwise use yt_dlp package.

    Returns:
        (str): The URL of the best quality MP4 video stream, or None if no suitable stream is found.
    """
    if use_pafy:
        # check_requirements(('pafy', 'youtube_dl==2020.12.2'))
        import pafy  # noqa
        return pafy.new(url).getbestvideo(preftype='mp4').url
    else:
        # check_requirements('yt-dlp')
        import yt_dlp
        with yt_dlp.YoutubeDL({'quiet': True}) as ydl:
            info_dict = ydl.extract_info(url, download=False)  # extract info
        for f in reversed(info_dict.get('formats', [])):  # reversed because best is usually last
            # Find a format with video codec, no audio, *.mp4 extension at least 1920x1080 size
            good_size = (f.get('width') or 0) >= 1920 or (f.get('height') or 0) >= 1080
            if good_size and f['vcodec'] != 'none' and f['acodec'] == 'none' and f['ext'] == 'mp4':
                return f.get('url')



class PushStream:
    def __init__(self, post_url, fps=None, img_size=None, q_size=60):
        if img_size is None:
            img_size = [640, 480]
        self.post_url=post_url
        self.fps=fps
        self.img_size=img_size #[640,480]
        self.last_frame=None
        self.q_size=q_size
        self.push_q=queue.Queue(q_size)
        self.img_init=self.creat_img()
        self.push_q.put(self.img_init)
        self.th=None

    def creat_img(self):
        try:
            img=cv2.imread("asset/run/loading.png")
            img=cv2.resize(img,(640,480))
            return img
        except:
            logger.warning("[pull]  加载初始图片失败")
            return np.zeros((480,640,3))

    def transform(self,img):
        #变换尺寸
        res=cv2.resize(img,self.img_size)

        return res




    def pipe_init(self):
        self.command = ['ffmpeg',
                        '-y',
                        '-f', 'rawvideo',
                        # '-vcodec', 'rawvideo',
                        '-pix_fmt', 'bgr24',
                        '-s', "{}x{}".format(self.img_size[0], self.img_size[1]),
                        # '-r', self.fps,
                        '-i', '-',
                        '-c:v', 'libx264',
                        # '-pix_fmt', 'yuv420p',
                        '-preset', 'ultrafast',
                        '-tune', 'zerolatency',
                        '-g', '25',
                        '-bf', '0',
                        '-bufsize', '2048k',
                        '-minrate', '300k',
                        '-maxrate', '2048k',
                        # '-flvflags','no_duration_filesize'# 不抛出异常
                        # '-c', 'copy',
                        '-f', 'flv',
                        self.post_url]

        return subprocess.Popen(self.command, shell=False, stdin=subprocess.PIPE)

    def push_th(self):
        time.sleep(2)#防止错误后无限开进程
        pipe=None
        try:
            pipe=self.pipe_init()
            logger.info(f"[push] 加载管道成功")
        except (Exception,BaseException) as e:
            logger.error(f"[push] 管带初始化错误")
            logger.error(f"[error] {traceback.format_exc()}")
            return
        last_frame=self.transform(self.push_q.get())
        while True:
            try:

                if self.push_q.qsize()>5:
                    img = self.push_q.get()
                    pipe.stdin.write(img.tobytes())
                    last_frame = img
                elif not self.fps is None:
                    pipe.stdin.write(last_frame.tobytes())

                if not self.fps is None:
                    time.sleep(1/int(self.fps))
                else:
                    time.sleep(0.04)


            except (Exception, BaseException) as e:
                logger.error(f"[push] 管带推流错误")
                logger.error(f"[error] {traceback.format_exc()}")
                return

    def push_img(self,img):
        if self.th is None or not self.th.is_alive():
            logger.info(f"[push] 开启推流进程")
            self.th=Thread(target=self.push_th, daemon=True)
            self.th.start()
        self.push_q.put(img)








if __name__ == '__main__':
    method=1
    if method==1:#拉流
        #load=LoadStreams("rtsp://admin:hxzh2019@192.168.6.192:554/h264/ch1/main/av_stream",imgsz=(640,480),buffer=False)
        load=LoadImages("/home/hxzh/Dataset/WaterDrop/103.mp4")
        # load=LoadStreams("https://www.youtube.com/watch?v=GhPYzKQCdMM",imgsz=(640,480),buffer=False)
        for i in load:
            (rtsp_url,images,_,_)=i[:4]
            print(rtsp_url)
            cv2.imshow("img",images[0])
            cv2.waitKey(1)

    elif method==2:#推流
        pu=PushStream("rtmp://192.168.6.144:31935/http_flv/test44",25)
        image = np.ones((640, 480, 3), dtype=np.uint8)

        image[40:140, :, :] = 255
        while True:
            pu.push_img(image)

            time.sleep(0.1)

